package com.aryankh.wordbookfx.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.extra.spring.SpringUtil;

import com.aryankh.wordbookfx.TaxStartApplication;
import com.aryankh.wordbookfx.constant.PathConstants;
import com.aryankh.wordbookfx.constant.ThemeColorConstants;
import com.aryankh.wordbookfx.entity.ReloadWordEntity;
import com.aryankh.wordbookfx.service.WordService;
import com.aryankh.wordbookfx.util.LocalFileUtils;
import com.aryankh.wordbookfx.util.SimpleWrite;
import com.aryankh.wordbookfx.util.SpringContextUtil;
import com.aryankh.wordbookfx.view.WordBookMainView;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Paint;
import org.jetbrains.annotations.NotNull;

import java.net.URL;
import java.util.*;

/**
 * @Author AryanKH
 * @Date 2023/4/26 11:18
 */
@FXMLController
public class ChangeController implements Initializable {
    @FXML
    private TableColumn<ReloadWordEntity, String> wordCol;

    @FXML
    private TableView<ReloadWordEntity> wordTableView;

    @FXML
    private TableColumn<ReloadWordEntity, String> explanationCol;

    @FXML
    private ToolBar mainBroad;

    @FXML
    private Button refreshBtn;

    @FXML
    private Button backBtn;

    @FXML
    private Button exportBtn;

    List<ReloadWordEntity> allWords;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        wordCol.setCellFactory(TextFieldTableCell.forTableColumn());
        explanationCol.setCellFactory(TextFieldTableCell.forTableColumn());
        String tableName = LocalFileUtils.getTableName();
        refresh(tableName);
        reloadTheme();
    }

    private void reloadTheme() {
        FileReader fileReader = new FileReader(PathConstants.C_THEME_NAME);
        if ("LightMode".equals(fileReader.readString())) {
            lightMod();
        } else if ("DarkMode".equals(fileReader.readString())) {
            darkMod();
        }
        // TableView 自定义样式
        wordTableView.setStyle("-fx-font-size: 12pt; ");
        wordCol.setStyle(" -fx-border-color: #2D4157; -fx-background-color: #CBCDD3; ");
        explanationCol.setStyle(" -fx-border-color: #2D4157; -fx-background-color: #CBCDD3;");
    }

    private void darkMod() {
        mainBroad.setBackground(new Background(new BackgroundFill(Paint
                .valueOf(ThemeColorConstants.MODENA_PURPLE), null, null)));
        wordTableView.setStyle("-fx-text-fill:#CED0D6;");
        explanationCol.setStyle("-fx-text-fill:#282A36; -fx-background-color: #CED0D6");
        wordCol.setStyle("-fx-text-fill:#282A36; -fx-background-color: #CED0D6");

        refreshBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));
        refreshBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        backBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));
        backBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

        exportBtn.setBackground(new Background(
                new BackgroundFill(Paint.valueOf(ThemeColorConstants.PURPLISH_BLACK), null, null)));
        exportBtn.setTextFill(Paint.valueOf(ThemeColorConstants.GRAY_WHITE));

    }

    private void lightMod() {

    }


    @FXML
    void onBack(MouseEvent event) {
        TaxStartApplication.showView(WordBookMainView.class);
    }

    private ObservableList<ReloadWordEntity> createObservableList(List<ReloadWordEntity> userList) {
        ObservableList<ReloadWordEntity> observableList = FXCollections.observableList(userList);
        wordCol.setCellValueFactory(new PropertyValueFactory<>("word"));
        explanationCol.setCellValueFactory(new PropertyValueFactory<>("explanation"));
        return observableList;
    }

    public void refresh(String tableName) {
        WordService wordService = SpringContextUtil.getBean(WordService.class);
        allWords = wordService.getAllWordsWithTableName(tableName);
        // 生成一个tableView可用的集合
        wordTableView.setItems(createObservableList(allWords));
    }


    @FXML
    void onWordEditCommit(TableColumn.CellEditEvent<ReloadWordEntity, String> event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        TablePosition<ReloadWordEntity, String> tablePosition = event.getTablePosition();
        int row = tablePosition.getRow();
        String word = event.getTableView().getItems().get(row).getWord();
        String explanation = event.getTableView().getItems().get(row).getExplanation();
        String newValue = event.getNewValue();
        if ("del".equals(newValue) || "DEL".equals(newValue)) {
            wordService.deleteWordWithTableName(word, explanation, LocalFileUtils.getTableName());
        } else {
            wordService.updateWordWithTableName(word, explanation, newValue, LocalFileUtils.getTableName());
        }
        refresh(LocalFileUtils.getTableName());
    }

    @FXML
    void onExplanationEditCommit(TableColumn.CellEditEvent<ReloadWordEntity, String> event) {
        WordService wordService = SpringUtil.getBean(WordService.class);
        TablePosition<ReloadWordEntity, String> tablePosition = event.getTablePosition();
        int row = tablePosition.getRow();
        String word = event.getTableView().getItems().get(row).getWord();
        String newValue = event.getNewValue();
        wordService.updateExplanationWithTableName(newValue, word, LocalFileUtils.getTableName());
        refresh(LocalFileUtils.getTableName());
    }


    @FXML
    void onExport(MouseEvent event) {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("Prepare for exporting");
        dialog.setHeaderText("Archive name: ");
        DialogPane dialogPane = dialog.getDialogPane();
        dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        TextField textField = new TextField();
        ChoiceBox<String> choiceBox = new ChoiceBox<>();
        choiceBox.getItems().addAll("sequence", "shuffle");
        choiceBox.setValue("sequence");
        VBox content = new VBox(textField, choiceBox);
        content.setSpacing(10);

        dialogPane.setContent(content);

        dialog.setResultConverter(buttonType -> {
            if (buttonType == ButtonType.OK) {
                String text = textField.getText();
                if (!"sequence".equals(choiceBox.getValue())) {
                    Collections.shuffle(allWords);
                    SimpleWrite.doWrite(text,allWords);
                }else {
                    List<ReloadWordEntity> order = ListUtil.sortByProperty(allWords, "word");
                    order.forEach(word-> System.out.println(word.getWord()));
                    SimpleWrite.doWrite(text,order);
                }

                getAlert(textField).showAndWait();
            }
            return null;
        });

        dialog.showAndWait();
    }

    @NotNull
    private static Alert getAlert(TextField textField) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("Export Succeed");
        alert.setHeaderText("Export Succeed:");
        alert.setContentText(PathConstants.C_PATH + textField.getText() + ".txt");
        return alert;
    }

    @FXML
    void onRefreshed(MouseEvent event) {
        refresh(LocalFileUtils.getTableName());
    }
}
